package com.atguigu.eduservice.controller;


import com.atguigu.commonutils.JwtUtils;
import com.atguigu.eduservice.client.UcenterClient;
import com.atguigu.eduservice.entity.EduComment;
import com.atguigu.eduservice.service.EduCommentService;
import com.atguigu.commonutils.R;
import com.atguigu.commonutils.ResponseEnum;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * <p>
 * 评论 前端控制器
 * </p>
 *
 * @author panDengZhu
 * @since 2024-04-21
 */
@Api(tags = "评论管理")
@RestController
//@CrossOrigin
@RequestMapping("/eduservice/comment")
public class EduCommentController {

    @Resource
    private EduCommentService commentService;

    @Resource
    private UcenterClient ucenterClient;

    /**
     * 分页查询评论
     *
     * @param page
     * @param limit
     * @param eduComment
     * @return
     */
    @ApiOperation("分页查询评论")
    @PostMapping("/getCommentList/{page}/{limit}")
    public R getCommentList(@ApiParam(value = "当前页数", required = true) @PathVariable long page,
                            @ApiParam(value = "每页记录数", required = true) @PathVariable long limit,
                            @RequestBody(required = false) EduComment eduComment) {

        Page<EduComment> pageParam = new Page<>(page, limit);
        Map<String, Object> map = commentService.getCommentList(pageParam, eduComment);


        return R.ok().data(map);
    }


    @ApiOperation("添加评论")
    @PostMapping("/auth/save")
    public R saveComment(@RequestBody EduComment eduComment, HttpServletRequest request) {
        //String token = request.getHeader("token");
        //System.out.println(token);
        //1.从header获取memberId
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        System.out.println(memberId);
        //2.判断memberId是否为空
        if (StringUtils.isBlank(memberId)) {
            return R.error().code(ResponseEnum.LOGIN_AUTH_ERROR.getCode()).message(ResponseEnum.LOGIN_AUTH_ERROR.getMessage());
        }
        eduComment.setMemberId(memberId);
        EduComment memberInfo = ucenterClient.getMemberInfo(memberId);
        eduComment.setNickname(memberInfo.getNickname());

        eduComment.setAvatar(memberInfo.getAvatar());

        commentService.save(eduComment);

        return R.ok();
    }

}

